#include "sk_storage/log.hpp"

#include <cstdio>

namespace sk_storage {
namespace log {

DiskItem::DiskItem(const std::string &key, const std::string &value) {
  using namespace std::chrono;
  key_ = key;
  value_ = value;
  log_id_ = sk_storage::easySnowflake.NewId();
}

DiskItem::DiskItem(std::string &&key, std::string &&value) {
  using namespace std::chrono;
  key_ = std::move(key);
  value_ = std::move(value);
  log_id_ = sk_storage::easySnowflake.NewId();
}

Status DiskItem::SerializeTo(std::string &serialize_str) {
  serialize_str = "";
  serialize_str.append(std::to_string(log_id_));
  serialize_str.push_back('|');
  serialize_str.append(key_);
  serialize_str.push_back('|');
  serialize_str.append(value_);
  return Status::OK;
}

Status DiskItem::UnSerializeTo(const std::string &un_serialize_str) {
  std::string sot;
  int cnt = 0;
  for (auto c : un_serialize_str) {
    if (c != '|') {
      sot.push_back(c);
    } else {
      if (cnt == 0) {
        log_id_ = std::stoull(sot);
      } else {
        key_ = sot;
      }
      sot = "";
      cnt++;
    }
  }
  if (cnt != 2) {
    return Status::LOG_FORMAT_ERR;
  }
  value_ = sot;
  return Status::OK;
}

Writer::Writer(const std::string &filename) {
  file_writer_ = new nec_fs::FileWriter(filename.c_str());
}

int Writer::Write(const std::string &log_info) {
  std::string log_info_line = log_info + '\n';
  return file_writer_->WriteStr(log_info_line.c_str());
}

Writer::~Writer() { delete file_writer_; }

Reader::Reader(const std::string &filename) {
  file_reader_ = new nec_fs::FileReader(filename.c_str());
}

int Reader::Read(std::string &log_info) {
  return file_reader_->ReadStr(log_info);
}

Reader::~Reader() {
  delete file_reader_;
}

} // namespace log
} // namespace sk_storage
